package cn.hqc.org.controller;


import cn.hqc.basic.utils.AjaxResult;
import cn.hqc.basic.utils.PageList;
import cn.hqc.org.domain.Department;
import cn.hqc.org.query.DepartmentQuery;
import cn.hqc.org.service.DepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@Controller
@RequestMapping("/dept")
@RestController
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    /**
     * 我们之前的方式定义接口
     */
//    @RequestMapping(value = "/findAll",method = RequestMethod.PATCH)
//    @ResponseBody
//    public List<Department> findAll(){
//        return departmentService.findAll();
//    }

    /**
     * restful风格
     */
    @GetMapping
    public List<Department> findAll() {
        return departmentService.findAll();
    }

    /**
     * 添加或者修改
     * 现在我们是前后端分离项目 我们前后端交互使用的是 json数据
     * json的本质是 字符串
     *
     * @RequestBody 把前端传过来的json转成我们的实体
     * 注意：@RequestBody 只能写一次
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department) {
        if (null == department.getId()) {
            // 添加
            departmentService.add(department);
        } else {
            // 修改
            departmentService.update(department);
        }
        return AjaxResult.success();
    }

    /**
     * 删除
     * 使用restful有一个 路径变量
     * 之前：http://localhost:8080?id=1&name=zhansan
     * 路径变量：http://localhost:8080/1
     */
    @DeleteMapping("/{id}")
//    @PreAuthorize(name = "删除部门",sn="department:delete")
    public AjaxResult delete(@PathVariable("id") Long id) {
        departmentService.delete(id);
        return AjaxResult.success();
    }

    /**
     * 查询一个
     */
    @ApiOperation(value = "通过ID查询" )
    @GetMapping("/{id}")
    public Department findById(@ApiParam(value="ID属性",required = true) @PathVariable("id") Long id) {
        return departmentService.findById(id);
    }

    /**
     * 分页查询
     */
    @PostMapping
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery query) {
        return departmentService.queryByPage(query);
    }

    /**
     * 批量删除
     */
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody List<Long> ids) {
         departmentService.batchDelete(ids);
         return AjaxResult.success();
    }

    /**
     * 无限级数
     */
    @GetMapping("/tree")
//    @PreAuthorize(name = "部门树",sn="department:tree")
    public List<Department> tree() {
        return departmentService.tree();
    }
}
